package flydove;

import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.concurrent.atomic.AtomicInteger;


public class FlyDoveClient {
	
	Socket socket;
	String recvDir ="C:\\Users\\LY\\Desktop\\培训\\git\\143\\";
	
	public static void main(String[] args) throws IOException {
		
		FlyDoveClient client = new FlyDoveClient();
		client.connect();
		client.recv();
		
		
		
	}

	

	private void connect() throws IOException {
		
		InetAddress localhos = InetAddress.getLocalHost();
		String ip = localhos.getHostAddress();//ip 192.168.0.143
		System.out.println("ip="+ip);
		int last = ip.lastIndexOf(".")+1;
		String prefix = ip.substring(0,last);//192.168.0
		
		//原子变量
		AtomicInteger count = new AtomicInteger(0);
		
		for(int i = 1; i<150;i++) {
			ip = prefix +i;
			InetAddress addr = InetAddress.getByName(ip);
			String _ip = ip;
			Thread t = new Thread(()-> {
				try {
					if(addr.isReachable(10)) {
						System.out.println("连接 IP = "+_ip);
						
						try {
						    socket = new Socket(_ip,8000);
							System.out.println("服务器连接成功！"+socket.getInetAddress());
						} catch (IOException e) {
//							e.printStackTrace();
						}
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
				count.set(count.get() + 1);
				synchronized (FlyDoveClient.this) {
					FlyDoveClient.this.notify();
				}
			});
			t.start();
		}
		while(count.get()<150) {
			synchronized (this) {
				try {
					this.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
	//接收文件
	private void recv() throws IOException {
		InputStream in = socket.getInputStream();
		DataInputStream dis = new DataInputStream(in);
		new Thread(()->{
			while(true) {
				try {
//					byte[]=new byte[1024];
//					int count = in.read(bytes);
//					String s = new String(bytes,0,count);
					String s = dis.readUTF();
					if(s.startsWith("dir:")) {
						String dirName = s.substring(4);
						recvDir(dirName);
					}else if(s.startsWith("file:")) {
						String dirName = s.substring(5);
						recvDir(dirName);
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}).start();
	}
	public void recvDir(String dirname) {
		File dir = new File(recvDir + dirname);
		if(dir.exists() == false) {
			dir.mkdir();
		}
	}
	
}










